package com.mes.system.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.model.RoleMember;
import com.mes.common.dao.BasicDao;
import com.mes.system.dao.iface.IEmployeeRoleDao;
import com.mes.system.domain.EmployeeRole;
import com.sun.mail.iap.Literal;

@Repository
public class EmployeeRoleDao extends BasicDao<EmployeeRole> implements IEmployeeRoleDao {
	@Override
	public void updateRoleMember(RoleMember roleMember) {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.update(roleMember);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void deleteRoleMember(RoleMember roleMember) {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.delete(roleMember);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void saveRoleMember(RoleMember roleMember) {
		Session session = this.getSessionFactory().getCurrentSession();
		try {
			session.save(roleMember);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public RoleMember getRoleMemberByEmpRole(String roleUid, String employeeUid) {
		Session session = this.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(RoleMember.class);
		
		criteria.add(Restrictions.and(Restrictions.eq("roleId", roleUid), 
				Restrictions.eq("username", employeeUid)));
		
		return  (RoleMember) criteria.list().get(0);
	}

	@Override
	public String getBdfRoleId(String roleUid) {
		String roleId = null;
		
		Session session = this.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(com.bstek.bdf2.core.model.Role.class);
		criteria.add(Restrictions.eq("name", roleUid));
		
		List<com.bstek.bdf2.core.model.Role> roles = criteria.list();
		
		if (roles.size() > 0){
			roleId = roles.get(0).getId();
		}
		
		return roleId;
	}
	
	/**
	 * 通过employeeUid查询相应的角色信息
	 * @param employeeUid
	 * @return
	 */
	public List<String> getEmployeeRoleByEmployeeUid(String employeeUid) {
		
		List<String> roleList = new ArrayList<>();
		List<EmployeeRole> list = new ArrayList<>();
		Session session = this.getSessionFactory().getCurrentSession();
		Criteria crit = session.createCriteria(EmployeeRole.class);
		crit.add(Restrictions.eq("employeeUid", employeeUid));
		list = crit.list();
		System.out.println(list);
		if(list != null) {
			for(EmployeeRole employeeRole:list) {
				roleList.add(employeeRole.getRoleUid());
			}
			return roleList;
		}
		return null;
	}

}
